package cn.com.bluemoon.daps.model.service.impl;

import cn.com.bluemoon.daps.common.domain.BaseModel;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.model.entity.DapDataModelGroup;
import cn.com.bluemoon.daps.model.entity.DapDataModelTableForeignKey;
import cn.com.bluemoon.daps.model.mapper.DapDataModelGroupMapper;
import cn.com.bluemoon.daps.model.mapper.DapDataModelTableForeignKeyMapper;
import cn.com.bluemoon.daps.model.service.DapDataModelGroupService;
import cn.com.bluemoon.daps.model.service.DapDataModelTableForeignKeyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class DapDataModelTableForeignKeyServiceImpl extends ServiceImpl<DapDataModelTableForeignKeyMapper, DapDataModelTableForeignKey>
        implements DapDataModelTableForeignKeyService {

    @Resource
    DapDataModelTableForeignKeyMapper dapDataModelTableForeignKeyMapper;

    /**
     * 删除外键关系
     * @param tableId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {DapException.class, Exception.class})
    public Boolean delForeignKey(String tableId, List<String> ids) {

        // 查询该表的所有外键
        List<DapDataModelTableForeignKey> tableForeignKeys = dapDataModelTableForeignKeyMapper
                .selectList(new LambdaQueryWrapper<DapDataModelTableForeignKey>()
                .eq(DapDataModelTableForeignKey::getModelTableId, tableId)
                .or().eq(DapDataModelTableForeignKey::getReferenceTableId, tableId));
        if(tableForeignKeys.isEmpty()){
            return true;
        }
        List<String> collect = tableForeignKeys.stream()
                .filter(t -> ids.contains(t.getModelTableFieldId()) || ids.contains(t.getReferenceFieldId()))
                .map(DapDataModelTableForeignKey::getId).collect(Collectors.toList());
        // 删除外键关系
        if(collect.isEmpty()){
            return true;
        }
        dapDataModelTableForeignKeyMapper.deleteBatchIds(collect);
        return dapDataModelTableForeignKeyMapper.deleteBatchIds(collect) >0 ? true : false;
    }

    /**
     * 根据表id删除外键
     * @param tableId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {DapException.class, Exception.class})
    public boolean delTableForeignKey(String tableId) {

        return dapDataModelTableForeignKeyMapper.delTableForeignTable(tableId);
    }

    /**
     * 更新或增加主健
     * @param keys
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = {DapException.class, Exception.class})
    public ResultBean<Boolean> updateOrInsertKey(List<DapDataModelTableForeignKey> keys) {

        //查询出新增的数据
        List<DapDataModelTableForeignKey> insert = keys.stream().filter(k -> StringUtils.isBlank(k.getId())).collect(Collectors.toList());
        List<DapDataModelTableForeignKey> list = Lists.newArrayList();
        if(!insert.isEmpty()){
            for(DapDataModelTableForeignKey key : insert){
                List<DapDataModelTableForeignKey> tableForeignKeys = this.getBaseMapper()
                        .selectList(new LambdaQueryWrapper<DapDataModelTableForeignKey>()
                        .in(DapDataModelTableForeignKey::getModelTableId, key.getModelTableId(), key.getReferenceTableId())
                        .in(DapDataModelTableForeignKey::getReferenceTableId, key.getReferenceTableId(), key.getModelTableId())
                        .eq(DapDataModelTableForeignKey::getBmStatus, BmStatus.ON.getCode()));
                if(!tableForeignKeys.isEmpty()){
                    list.addAll(tableForeignKeys);
                }
            }
        }
        // 如果为空，表示数据库中不存在该外键关系
        if(list.isEmpty()){
            return ResultBean.ok(this.saveOrUpdateBatch(keys));
        }else {
            return ResultBean.error("两张表之间不能存在多条外键关系！");
        }
    }
}
